package com.thirteenClassicsServer.service.impl;

import static com.thirteenClassicsServer.service.impl.XmlParseService.toGetTableName;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.thirteenClassics.context.BaseContext;
import com.thirteenClassics.dto.BookDto;
import com.thirteenClassics.dto.BookPageQueryDTO;
import com.thirteenClassics.entity.Book;
import com.thirteenClassics.exception.BaseException;
import com.thirteenClassics.result.PageResult;
import com.thirteenClassicsServer.mapper.BookMapper;
import com.thirteenClassicsServer.mapper.CatalogBookMapper;
import com.thirteenClassicsServer.mapper.PictureMapper;
import com.thirteenClassicsServer.mapper.SentenceMapper;
import com.thirteenClassicsServer.service.IBookService;

@Service
public class BookServiceImpl implements IBookService {
    @Resource
    private BookMapper bookMapper;
    @Resource
    private CatalogBookMapper catalogBookMapper;
    @Resource
    private SentenceMapper sentenceMapper;

    @Resource
    private PictureMapper pictureMapper;

    public static boolean judge(String bookLang, String currentLang) {
        // 分割字符串成语言列表
        String[] languages1 = bookLang.split("\\s+");
        List<String> languages2 = Arrays.asList(currentLang.split("\\s+"));

        // 遍历第一个列表中的每个语言
        for (String language1 : languages1) {
            // 检查是否包含在第二个列表中的任何语言
            if (languages2.contains(language1)) {
                return true;
            }
        }

        // 没有找到匹配的语言
        return false;
    }

    @Override
    public PageResult pageQuery(BookPageQueryDTO bookPageQueryDTO) {
        PageHelper.startPage(bookPageQueryDTO.getPage(), bookPageQueryDTO.getPageSize());
        bookPageQueryDTO.setJdbFlag(Long.valueOf(0));
        Page<Book> page = bookMapper.pageQuery(bookPageQueryDTO);
        Page<BookDto> page1 = new Page<>();

        //只显示该用户涉及到的语言,包含为1，不包含为0
        for (Book book : page) {
            BookDto bookDto = new BookDto();
            BeanUtils.copyProperties(book, bookDto);
            if (judge(book.getBookLang(), BaseContext.getCurrentLang())) {
                bookDto.setFlag(Long.valueOf(1));
            } else {
                bookDto.setFlag(Long.valueOf(0));
            }


            String lang = book.getBookLang();
            // 使用空格分隔字符串并转换为列表
            ArrayList<String> characterList = new ArrayList<>(Arrays.asList(lang.trim().split(" ")));

            bookDto.setBookLang(characterList);
            page1.add(bookDto);
        }
        return new PageResult(page.getTotal(), page1.getResult());
    }

    @Override
    public PageResult pageQueryjdb(BookPageQueryDTO bookPageQueryDTO) {
        PageHelper.startPage(bookPageQueryDTO.getPage(), bookPageQueryDTO.getPageSize());
        bookPageQueryDTO.setJdbFlag(Long.valueOf(1));
        bookPageQueryDTO.setCreateFlag(Long.valueOf(1));
        Page<Book> page = bookMapper.pageQuery(bookPageQueryDTO);
        Page<BookDto> page1 = new Page<>();

        //只显示该用户涉及到的语言,包含为1，不包含为0
        for (Book book : page) {
            BookDto bookDto = new BookDto();
            BeanUtils.copyProperties(book, bookDto);
            if (judge(book.getBookLang(), BaseContext.getCurrentLang())) {
                bookDto.setFlag(Long.valueOf(1));
            } else {
                bookDto.setFlag(Long.valueOf(0));
            }


            String lang = book.getBookLang();
            // 使用空格分隔字符串并转换为列表
            ArrayList<String> characterList = new ArrayList<>(Arrays.asList(lang.trim().split(" ")));

            bookDto.setBookLang(characterList);
            page1.add(bookDto);
        }
        return new PageResult(page.getTotal(), page1.getResult());
    }

    @Override
    public Long saveBook(Book book) {
        List<Book> book1 = bookMapper.selectbook(book);
        if (book1.size() != 0) {
            throw new BaseException("书名重复添加");
        }

        book.setCreateTime(LocalDateTime.now());
        book.setJdbFlag(0);

        bookMapper.insert(book);
        return book.getId();
    }

    public Long saveBookJdb(Book book) {
        List<Book> book1 = bookMapper.selectbookJdb(book);
        if (book1.size() != 0) {
            throw new BaseException("书名重复添加");
        }

        book.setCreateTime(LocalDateTime.now());
        book.setBookLang("藏语(现代) 藏语(古代) 蒙古语(现代) 蒙古语(古代) 西夏文 满文");
        book.setJdbFlag(1);

        bookMapper.insert(book);
        return book.getId();
    }

    @Transactional
    @Override
    public void deleteBatch(List<Long> ids) {

        //删除书目数据
        // 1.删除book表记录
        // 2.删除catalog_minority表的bk_id记录
        // 3.删除picture表记录
        for (Long id : ids) {
            Book book = bookMapper.selectbookById(id);
            if (book.getJdbFlag().equals(1)) {
                throw new BaseException("id错误，不能删经典版");
            }
            bookMapper.deleteById(id);

            catalogBookMapper.updateMinorityBkIdTONull(id);

            List<Long> entryIds = catalogBookMapper.selectIdByBookId(id);
            if (!entryIds.isEmpty()) {
                pictureMapper.updateEntryIdToNullBatch(entryIds);
            }


            String tableName = toGetTableName(book.getBookName());
            for (Long entryId : entryIds) {
                sentenceMapper.deleteSentenceByEntryId(entryId, tableName);
            }
        }

    }

    @Override
    public void updateBook(Book book) {

        bookMapper.update(book);
    }

    @Override
    public Book selectbookById(Long id) {

        return bookMapper.selectbookById(id);
    }
}
